import React, {useCallback, useRef, useState} from 'react';
import {Form, Input, Space, Button, FormRule, message} from "antd";
import axios from 'axios';
import styles from './app.module.scss';
import {ImageUpload, Editor, type RcFileWithUrl} from "./components";
import {RcFile} from "antd/es/upload";

function App() {

  const files = useRef<RcFileWithUrl[]>([]);
  const content = useRef<string>();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const requiredRule: FormRule[] = [
    {
      required: true,
    }
  ];
  const coverRule: FormRule[] = [
    {
      required: true,
      validateTrigger: '',
      validator(){
        if(!files.current.length){
          return Promise.reject('没传图');
        }else{
          return Promise.resolve();
        }
      }
    },
  ];
  const contentRule: FormRule[] = [
    {
      required: true,
      validator(){
        console.log(content.current);
        if(!content.current?.length){
          return Promise.reject('没写内容');
        }else{
          return Promise.resolve();
        }
      },
    },
  ];

  const onFinish = useCallback(async ()=>{
    try{
      setLoading(true);
      const fields = await form.validateFields();
      const formData = new FormData();
      for(const img of files.current){
        formData.append('file', img as RcFile);
      }
      const imgsRes = await axios.post('http://120.46.170.54:8801/api/Stalls/upload', formData);
      const data: any = {
        ...fields,
        boothTile: fields.title,
        description: content.current,
        imgs: imgsRes.data.data.join(',')
      };
      const createRes = await axios.post('http://120.46.170.54:8801/api/Stalls/create', data);
      if(createRes.data.success){
        message.success('创建成功');
      }
    }catch (e){
      message.error('创建失败');
    }finally {
      setLoading(false);
    }
  },[]);

  const onCoverChange = useCallback((value: RcFileWithUrl[])=>{
    files.current = value
  }, []);

  return (
    <div className={styles.wrapper}>
      <Form style={{width: '600px'}} form={form} onFinish={onFinish}>
        <Form.Item label='标题' name='title' rules={requiredRule}>
          <Input/>
        </Form.Item>
        <Form.Item label='内容' name='description' rules={contentRule}>
          <Editor onChange={value => content.current = value} />
        </Form.Item>
        <Form.Item label='封面图' name='imgs' rules={coverRule}>
          <ImageUpload onChange={onCoverChange} />
        </Form.Item>
        <Form.Item label='坐标点' name='boothLocation' rules={requiredRule}>
          <Space.Compact>
            <Input />
          </Space.Compact>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;
